<script setup lang="ts">
import { io } from 'socket.io-client'
import 'webrtc-adapter'

enum roleType {
	sender = 'sender',
	receiver = 'receiver',
}

enum socketEvent {
	connect = 'connect',
	receiverJoin = 'receiverJoin',
	toIO = 'toIO',
	toSocket = 'toSocket',
	receiverAsk = 'receiverAsk',
	success = 'success',
	disconnect = 'disconnect',
}

const dialogVisible = ref(true)
const remoteVideo = ref<HTMLVideoElement>()
const remotePlay = () => {
	socket.emit(socketEvent.receiverAsk, { roomId: roomId.value })

	console.log('[请求播放]')
}
const roomId = ref('')
const buddy = new RTCPeerConnection()
const beforeClose = () => {
	dialogVisible.value = false

	if (roomId.value !== '') {
		socket.emit(socketEvent.receiverJoin, { roomId: roomId.value })
		socket.on(socketEvent.success, () => {
			toast.success(`成功加入房间`)
		})
	} else {
		toast.warning(`房间密码无效\n请刷新页面重试`)
	}
}

const socket = io(`https://${location.hostname}:8099`, {
	reconnection: false,
	transports: ['websocket'],
	query: {
		role: roleType.receiver,
	},
})

socket.on(socketEvent.connect, () => {
	toast.success(`我的ID是\n${socket.id}\n已连接${location.hostname}:8099`)
})

socket.on(socketEvent.toSocket, async (data) => {
	const { type, sdp, iceCandidate } = data
	console.log(type)
	switch (type) {
		case 'offer':
			buddy.setRemoteDescription(new RTCSessionDescription({ type, sdp }))
			const answer = await buddy.createAnswer()
			await buddy.setLocalDescription(answer)
			socket.emit(socketEvent.toIO, {
				type: answer.type,
				sdp: answer.sdp,
				roomId: roomId,
			})
			break

		case 'offer_ice':
			buddy.addIceCandidate(iceCandidate)
			break

		default:
			break
	}
})

socket.on(socketEvent.disconnect, () => {
	toast.error('失去连接')
})

onMounted(() => {
	buddy.ontrack = function (e) {
		remoteVideo.value!.srcObject = e.streams[0]
		remoteVideo.value?.play()
	}

	buddy.onicecandidate = function (e) {
		if (e.candidate) {
			socket.emit(socketEvent.toIO, {
				type: 'answer_ice',
				iceCandidate: e.candidate,
				roomId: roomId,
			})
		}
	}
})
</script>

<template>
	<el-container class="w-full">
		<el-main>
			<video ref="remoteVideo"></video>
		</el-main>
		<el-footer>
			<button
				ref="enjoy-button"
				type="button"
				class="w-full h-20 font-size-15 text-light-200 bg-sky-300 border-blue-400 rounded-lg"
				@click="remotePlay"
			>
				观看直播
			</button>
		</el-footer>
	</el-container>

	<el-dialog
		v-model="dialogVisible"
		:before-close="beforeClose"
		title="进入房间"
		width="500"
	>
		<el-input v-model="roomId" placeholder="请输入房间密码" clearable />
		<template #footer>
			<div class="dialog-footer">
				<el-button type="primary" @click="beforeClose">
					确定
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<style></style>
